package com.jianjun.project.system.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.exception.ServiceException;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.framework.web.interceptor.DataScopeInterceptor;
import com.jianjun.project.common.model.SysPost;
import com.jianjun.project.common.model.SysRole;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.common.model.SysUserPost;
import com.jianjun.project.common.model.SysUserRole;
import com.jianjun.project.system.config.SysConfigService;
import com.jianjun.project.system.dept.SysDeptService;
import com.jianjun.project.system.post.SysPostService;
import com.jianjun.project.system.role.SysRoleService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 *
 * @author source
 * {@code @date} 2025/1/9 14:20
 */
@Slf4j
public class SysUserService {
    private final SysUser dao = new SysUser().dao();
    @Inject
    SysConfigService configService;
    @Inject
    SysRoleService roleService;
    @Inject
    SysPostService postService;
    @Inject
    SysDeptService deptService;

    public Page<SysUser> paginate(SysUser model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()).set(DataScopeInterceptor.getDataScope()).set(model.getColumnAsc()));
        return dao.paginate(model.getPageNum(), model.getPageSize(), sqlParaDb);
    }


    public List<SysUser> selectUserList(Model<SysUser> model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()).set(DataScopeInterceptor.getDataScope()));
        return dao.find(sqlParaDb);
    }

    public SysUser selectUserFirst(Model<SysUser> model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()));
        return dao.findFirst(sqlParaDb);
    }

    public SysUser selectUserById(Long userId) {
        return dao.findById(userId);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     */
    public Page<SysUser> selectAllocatedList(SysUser model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()).set("roleId", model.getRoleId()).set(model.getColumnAsc()));
        return dao.paginate(model.getPageNum(), model.getPageSize(), sqlParaDb);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     */
    public Page<SysUser> selectUnallocatedList(SysUser model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()).set("roleNoId", model.getRoleId()).set(model.getColumnAsc()));
        return dao.paginate(model.getPageNum(), model.getPageSize(), sqlParaDb);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    public int resetUserPwd(String userName, String password) {
        return Db.template("resetUserPwd", password, userName).update();
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar 头像地址
     * @return 结果
     */
    public boolean updateUserAvatar(String userName, String avatar) {
        return Db.template("updateUserAvatar", avatar, userName).update() > 0;
    }


    public SysUser selectUserByUserName(String userName) {
        SysUser model = new SysUser();
        model.setUserName(userName);
        return selectUserFirst(model);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    public String selectUserRoleGroup(Long userId) {
        List<SysRole> list = roleService.selectRolesByUserId(userId);
        if (CollectionUtil.isEmpty(list)) {
            return StrUtil.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(Constants.DELIMETER));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    public String selectUserPostGroup(Long userId) {
        List<SysPost> list = postService.selectPostListByUserId(userId);
        if (CollectionUtil.isEmpty(list)) {
            return StrUtil.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(Constants.DELIMETER));
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean resetPwd(SysUser user) {
        return updateRoleDb(user);
    }


    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean updateUserProfile(SysUser user) {
        return updateRoleDb(user);
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     */
    public boolean checkPhoneUnique(SysUser user) {
        long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser model = new SysUser();
        model.setPhonenumber(user.getPhonenumber());
        SysUser info = selectUserFirst(model);
        if (Objects.nonNull(info) && info.getUserId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     */
    public boolean checkEmailUnique(SysUser user) {
        long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser model = new SysUser();
        model.setEmail(user.getEmail());
        SysUser info = selectUserFirst(model);
        if (Objects.nonNull(info) && info.getUserId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean checkUserNameUnique(SysUser user) {
        long userId = Objects.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser model = new SysUser();
        model.setUserName(user.getUserName());
        SysUser info = selectUserFirst(model);
        if (Objects.nonNull(info) && info.getUserId() != userId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = selectUserList(user);
            if (CollectionUtil.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    public void checkUserAllowed(SysUser user) {
        if (Objects.nonNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean updateUserStatus(SysUser user) {
        return updateRoleDb(user);
    }


    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Before(Tx.class)
    public boolean insertUser(SysUser user) {
        // 新增用户信息
        boolean res = registerUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return res;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    public boolean registerUser(SysUser user) {
        user.setCreateTime(new Date());
        return user.save();
    }

    public boolean updateRoleDb(SysUser user) {
        user.setUpdateTime(new Date());
        return user.update();
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Before(Tx.class)
    public boolean updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        SysUserPost model1 = new SysUserPost();
        model1.setUserId(userId);
        Db.template("deleteUserRole", Kv.of("cond", model1.toMap())).update();
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        SysUserPost model2 = new SysUserPost();
        model2.setUserId(userId);
        Db.template("deleteUserPost", Kv.of("cond", model2.toMap())).update();
        // 新增用户与岗位管理
        insertUserPost(user);
        user.setUpdateTime(new Date());
        return updateRoleDb(user);
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (ArrayUtil.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            Db.batchSave(list, list.size());
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Before(Tx.class)
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            SysUser model = new SysUser();
            model.setUserId(userId);
            checkUserAllowed(model);
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        Db.template("deleteUserRole", Kv.of("userIds", userIds)).update();
        // 删除用户与岗位关联
        Db.template("deleteUserPost", Kv.of("userIds", userIds)).update();
        return Db.template("deleteUser", Kv.of("userIds", userIds)).update();
    }

    /**
     * 用户授权角色
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Before(Tx.class)
    public void insertUserAuth(Long userId, Long[] roleIds) {
        SysUserRole model = new SysUserRole();
        model.setUserId(userId);
        Db.template("deleteUserRole", Kv.of("cond", model.toMap())).update();
        insertUserRole(userId, roleIds);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (ArrayUtil.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            Db.batchSave(list, list.size());
        }
    }


    /**
     * 导入用户数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (CollectionUtil.isEmpty(userList)) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = selectUserByUserName(user.getUserName());
                if (Objects.isNull(u)) {
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    registerUser(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 导入成功");
                } else if (isUpdateSupport) {
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    updateRoleDb(user);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、账号 ").append(user.getUserName()).append(" 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(user.getUserName()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
